package com.woyao;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.woyao.core.model.ApplyResponse;
import com.woyao.core.model.Appointment;
import com.woyao.core.model.BaseResponse;
import com.woyao.core.model.Conversation;
import com.woyao.core.model.DemandSummary;
import com.woyao.core.model.GetMessageResponse;
import com.woyao.core.model.GetMyDemandResponse;
import com.woyao.core.model.Talk;
import com.woyao.core.service.AccountService;
import com.woyao.core.service.ChanceService;
import com.woyao.core.util.CollectionUtil;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;
import com.woyao.core.util.StringUtil;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;

import static com.woyao.WoyaoooApplication.userId;

public class TalkActivity extends AppCompatActivity {
    ProgressDialog progressDialog;
    GetMessageResponse current = new GetMessageResponse();

    private LinearLayout talkView;
    private LinearLayout participants;
    LinearLayout talkApply;
    LinearLayout talkQuit;

    String type = "match";

    private ClipboardManager myClipboard;
    private ClipData myClip;
    private TextView descTxt;
    private EditText content;
    private Button sendButton;
    private Button mgmtButton;

    private List<Talk> talks ;
    private  Integer tid =0;
    private  Integer bid =0;
    Conversation cur = new Conversation();
    private ScrollView chatScroll ;
    private View typingIndicator = null;

    private LinearLayout actionArea;
    private Integer ADD_DEMAND_CODE = 600;

    private Integer CONFIRM_RELATION_CODE = 1000;


    private HashMap<String, Appointment> appoints = new HashMap<String, Appointment>() ;

    private String current_appoint_id = "0";

    private Integer RELATION_CODE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_talk);



        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final ActionBar ab = getSupportActionBar();
        ab.setDisplayShowHomeEnabled(true); // show or hide the default home button
        ab.setDisplayHomeAsUpEnabled(true);
        ab.setDisplayShowCustomEnabled(true); // enable overriding the default toolbar layout


        chatScroll = (ScrollView)findViewById(R.id.chat_scroll);

        content = (EditText)findViewById(R.id.talk_content);

        actionArea = (LinearLayout) findViewById(R.id.talk_actions);

        participants = (LinearLayout) findViewById(R.id.participants);

        descTxt = (TextView) findViewById(R.id.id_talk_description);


        talkApply = (LinearLayout) findViewById(R.id.id_talk_apply);

        talkApply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                applyDemand();
//
//                Intent intent = new Intent();
//                intent.setClass(TalkActivity.this, RelationActivity.class);
//
//                intent.putExtra("is_new",false);
//                intent.putExtra("id",current.getContent().getPartner_id());
//                intent.putExtra("mid",current.getContent().getId());
//                startActivityForResult(intent,CONFIRM_RELATION_CODE);

//                if ( current.getContent().getStatus().equals("oneway") ) {
//
//                    Dialog alertDialog = new AlertDialog.Builder(TalkActivity.this).
//                            setTitle("信息").
//                            setMessage("达成意向合作共识吗").
//                            setIcon(R.drawable.ic_launcher).
//                            setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//
//                                }
//                            }).
//                            setNegativeButton("取消", new DialogInterface.OnClickListener() {
//
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//
//                                }
//                            }).
//                            create();
//                    alertDialog.show();
//                }else {
//                    applyDemand();
//                }
            }
        });

         talkQuit = (LinearLayout) findViewById(R.id.id_talk_quit);

        talkQuit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ( current.getContent().getStatus().equals("match") ){
                    Common.alert(TalkActivity.this, "尚未建立沟通");
                    return;
                }

                Dialog alertDialog = new AlertDialog.Builder(TalkActivity.this).
                        setTitle("不合适？").
                        setMessage("消息将不再通知").
                        setIcon(R.drawable.ic_launcher).
                        setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                quit();
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).
                        create();
                alertDialog.show();

            }
        });


        sendButton  = (Button) findViewById(R.id.send_talk);

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendTalk();
            }
        });

        mgmtButton  = (Button) findViewById(R.id.talk_report);

        mgmtButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getIt( tid );
            }
        });


        Intent intent = getIntent();
        tid = intent.getIntExtra("id",0);
        bid = intent.getIntExtra("bid",0);
        type = intent.getStringExtra("type");
        if (type == null){
            type = "match";
        }

        talkView=(LinearLayout)findViewById(R.id.chat_list);


        loadTalks();




    }

    private void getIt( final Integer partner_id ){

        Intent intent = new Intent();
        intent.setClass(TalkActivity.this, RelationActivity.class);
        intent.putExtra("id",partner_id);
        startActivityForResult(intent, RELATION_CODE);
    }


    private void renderPartners(){
        participants.removeAllViews();
        if (CollectionUtil.notEmpty(cur.getParticipants())) {
            //合作的人

            for (final com.woyao.core.model.PartnerSummary partner : cur.getParticipants()) {

                LinearLayout item = (LinearLayout) LayoutInflater.from(TalkActivity.this).inflate(R.layout.partner_summary_item, null);
                final ImageView demandImage = (ImageView) item.findViewById(R.id.partner_demand_image);
                final  CircleImageView snailview = (CircleImageView) item.findViewById(R.id.partner_avatar);
                final TextView title = (TextView) item.findViewById(R.id.partner_title);
                final TextView desc = (TextView) item.findViewById(R.id.partner_desc);
                final TextView displayname = (TextView) item.findViewById(R.id.partner_displayname);
                final Button call = (Button) item.findViewById(R.id.partner_call);
                final Button wechat = (Button) item.findViewById(R.id.partner_wechat);
                final Button email = (Button) item.findViewById(R.id.partner_email);
                final Button office = (Button) item.findViewById(R.id.partner_office);
//                final Button toggleBtn = (Button) item.findViewById(R.id.partner_delete);
                final LinearLayout info = (LinearLayout) item.findViewById(R.id.partner_info);

                if (partner.getMobile().equals("")) {
                    call.setVisibility(View.GONE);
                }

//                if (partner.getDeletable()){
//                    toggleBtn.setVisibility(View.VISIBLE);
//                }else{
//                    toggleBtn.setVisibility(View.GONE);
//                }

                title.setText(partner.getTitle());
                desc.setText(partner.getDescription());
                displayname.setText( partner.getDisplayname());

                if (StringUtil.notNullOrEmpty(partner.getSnailview())) {
                    Picasso.with(this)
                            .load(partner.getSnailview())
                            .into(snailview);
                }




                call.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(Intent.ACTION_DIAL);
                        Uri data = Uri.parse("tel:" + partner.getMobile());
                        intent.setData(data);
                        startActivity(intent);
                    }
                });

                if (partner.getWechat().equals("")){
                    wechat.setVisibility(View.GONE);
                }

                wechat.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Dialog alertDialog = new AlertDialog.Builder(TalkActivity.this).
                                setTitle("微信号").
                                setMessage(partner.getWechat()).
                                setIcon(R.drawable.ic_launcher).
                                setPositiveButton("复制", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                                        myClip = ClipData.newPlainText("text", partner.getWechat());
                                        myClipboard.setPrimaryClip(myClip);
                                    }
                                }).
                                create();
                        alertDialog.show();
                    }
                });

                if (partner.getEmail().equals("")){
                    email.setVisibility(View.GONE);
                }

                email.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Dialog alertDialog = new AlertDialog.Builder(TalkActivity.this).
                                setTitle("电子邮件").
                                setMessage(partner.getEmail()).
                                setIcon(R.drawable.ic_launcher).
                                setPositiveButton("复制", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                                        myClip = ClipData.newPlainText("text", partner.getEmail());
                                        myClipboard.setPrimaryClip(myClip);
                                    }
                                }).
                                create();
                        alertDialog.show();
                    }
                });

                if (partner.getOffice().equals("")){
                    office.setVisibility(View.GONE);
                }
                office.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Dialog alertDialog = new AlertDialog.Builder(TalkActivity.this).
                                setTitle("办公地址").
                                setMessage(partner.getOffice()).
                                setIcon(R.drawable.ic_launcher).
                                setPositiveButton("复制", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                                        myClip = ClipData.newPlainText("text", partner.getOffice());
                                        myClipboard.setPrimaryClip(myClip);
                                    }
                                }).
                                create();
                        alertDialog.show();
                    }
                });

//                toggleBtn.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        Dialog alertDialog = new AlertDialog.Builder(RelationActivity.this).
//                                setTitle("信息").
//                                setMessage("删除合作成员吗？").
//                                setIcon(R.drawable.ic_launcher).
//                                setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//                                        deletePartner( partner.getUser_id());
//                                    }
//                                }).
//                                setNegativeButton("取消", new DialogInterface.OnClickListener() {
//
//                                    @Override
//                                    public void onClick(DialogInterface dialog, int which) {
//
//                                    }
//                                }).
//                                create();
//                        alertDialog.show();
//                    }
//                });


                snailview.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                        intent.putExtra("id",partner.getUser_id() );
                        intent.setClass(TalkActivity.this, PersonViewActivity.class);
                        startActivity(intent);

                    }
                });
                info.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        if (partner.getDemand_id() >0 ){
                            Intent intent = new Intent();
                            intent.putExtra( "id", partner.getDemand_id());
                            intent.setClass( TalkActivity.this, ChanceViewActivity.class);
                            startActivity(intent );
                        }else{
                            Common.alert(TalkActivity.this,"合作方业务未确认");
                        }

                    }
                });

                participants.addView(item);
                View splitter = (View) LayoutInflater.from(TalkActivity.this).inflate(R.layout.splitter, null);
                participants.addView(splitter);
            }
        }

    }
    private void applyDemand(  ){

        AsyncTask<Void, Void, GetMyDemandResponse> task =new AsyncTask<Void, Void, GetMyDemandResponse>() {
            @Override
            protected GetMyDemandResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetMyDemandResponse> responseCall = svc.getMyDemand(WoyaoooApplication.userId, "false");
                try {
                    GetMyDemandResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetMyDemandResponse response) {
                    presentChoice(response.getContent());
            }
            @Override
            protected void onCancelled() {

            }
        };
        task.execute((Void)null);

    }
    public  void AddDemand(){
        Intent intent = new Intent();
        intent.putExtra("from", "talk"  );
        intent.putExtra("is_new", true);
        intent.setClass(TalkActivity.this, DemandNewActivity.class);
        startActivityForResult(intent, ADD_DEMAND_CODE);
    }

    int yourChoice = 0 ;
    private void presentChoice( final List<DemandSummary> demands ){

        if (demands.size() == 0){
            AddDemand();
            return;
        }

        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < demands.size(); i++) {
            DemandSummary ds = demands.get(i);
            list.add(ds.getTitle());
        }

        String[] items =  (String[])list.toArray(new String[0]);

        AlertDialog.Builder singleChoiceDialog =
                new AlertDialog.Builder(TalkActivity.this);
        singleChoiceDialog.setTitle("表达合作意向");
        // 第二个参数是默认选项，此处设置为0
        singleChoiceDialog.setSingleChoiceItems(items, yourChoice,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        yourChoice = which;
                    }
                });
        singleChoiceDialog.setPositiveButton("确 定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (yourChoice != -1) {
                            applyIt(demands.get(yourChoice).getId());
                        }
                    }
                });
        singleChoiceDialog.setNegativeButton("取 消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        singleChoiceDialog.show();

    }


    private void applyIt( final Integer demand_id ) {

        progressDialog = new ProgressDialog(TalkActivity.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在邀约沟通···");
        progressDialog.show();



        AsyncTask<Void, Void, ApplyResponse> task =
                new AsyncTask<Void, Void, ApplyResponse>() {


                    @Override
                    protected ApplyResponse doInBackground(Void... params) {
                        ChanceService svc = ServiceFactory.get(ChanceService.class);

                        Call<ApplyResponse> responseCall = svc.apply(userId,"", current.getContent().getRelation_demand_id(),demand_id  ,current.getContent().getPartner_id(),0);
                        try {
                            ApplyResponse response = responseCall.execute().body();
                            return  response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final ApplyResponse response) {
                        progressDialog.dismiss();
                        if ( response != null) {
                            if (response.isSuccess()) {
                                Common.alert(TalkActivity.this,"已经表达了意向。" );
                                loadTalks();
//                                Toast.makeText(TalkActivity.this,"已经表达了合作意向。",Toast.LENGTH_SHORT).show();
                            }else{
                                alertAndCharge( response);
//                                Common.alert(TalkActivity.this,response.getMessage() );
//                                Toast.makeText(TalkActivity.this,response.getMessage(),Toast.LENGTH_SHORT).show();
                            }

                        }else{
                            Common.showSnack(TalkActivity.this, sendButton,"抱歉,处理失败，请重试。");
                        }
                    }

                    @Override
                    protected void onCancelled() {
                        progressDialog.dismiss();
                        Common.showSnack(TalkActivity.this, sendButton,"抱歉,处理失败，请重试。");
                    }
                };
        task.execute((Void) null);

    }

    public void renderVerify(){
        Intent intent = new Intent();
        intent.setClass(TalkActivity.this, VerifyActivity.class);
        startActivity(intent);
    }

    private void renderMoney( ){
        Intent intent = new Intent();
        intent.putExtra("money", 100.0);
        intent.setClass(TalkActivity.this, MoneyActivity.class);
        startActivity(intent);
    }

    private void alertAndCharge(final ApplyResponse response ){


        Dialog alertDialog = new AlertDialog.Builder(TalkActivity.this).
                setTitle("信息").
                setMessage(response.getMessage()).
                setIcon(R.drawable.ic_launcher).
                setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        if (response.getCondition().equals("charge") ){
                            renderMoney();
                        }

                        if (response.getCondition().equals("verify") ){
                            renderVerify();
                        }
                    }
                }).
                create();
        alertDialog.show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if  (requestCode == ADD_DEMAND_CODE && resultCode ==666 ){
            Integer demand_id = data.getIntExtra("demand_id",0);
            if (demand_id == 0) return;
            applyIt( demand_id );

        }

        if  (requestCode == CONFIRM_RELATION_CODE && resultCode ==666 ){
            loadTalks();

        }

        if(requestCode == RELATION_CODE  && resultCode == 666 ) {
            Boolean ischanged = data.getBooleanExtra("changed", true);
            if (ischanged) {
                loadTalks();
            }

        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        finish();
        return true;
    }

    private void quit() {

        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected BaseResponse doInBackground(Void... params) {
                ChanceService svc = ServiceFactory.get(ChanceService.class);
                Call<BaseResponse> responseCall = svc.quit(userId, cur.getMid(),current.getContent().getPartner_id());
                try {
                    BaseResponse r = responseCall.execute().body();
                    return r;
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }

            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
                if (response != null ) {
                    Toast.makeText(TalkActivity.this,response.getMessage(),Toast.LENGTH_SHORT).show();
                } else {
                    Common.showSnack(TalkActivity.this,sendButton,"网络错误，请重试");
                }

            }

            @Override
            protected void onCancelled() {

            }
        };
        task.execute((Void) null);
    }


    private void loadTalks() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("拼命加载中······");
        progressDialog.show();

        AsyncTask<Void, Void, GetMessageResponse> task = new AsyncTask<Void, Void, GetMessageResponse>() {
            @Override
            protected GetMessageResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetMessageResponse> responseCall = svc.getMessage(userId, tid, type,bid);
                try {
                    GetMessageResponse r = responseCall.execute().body();
                    return r;
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }

            }

            @Override
            protected void onPostExecute(final GetMessageResponse response) {
                progressDialog.dismiss();
                if (response != null ) {
                    render( response );
                } else {
                    Common.showSnack(TalkActivity.this,sendButton,"网络错误，请重试");
                }

            }

            @Override
            protected void onCancelled() {

            }
        };
        task.execute((Void) null);
    }

    private  void render(GetMessageResponse tr ){


        current = tr;
        cur = tr.getContent();
        descTxt.setText( tr.getContent().getDescription() );

        renderPartners();
        this.setTitle( cur.getTitle() );
//        if (cur.getRelation_user_id() > 0 ){
//            mgmtButton.setVisibility(View.VISIBLE);
//        }else{
//            mgmtButton.setVisibility(View.GONE);
//        }

        if (cur.getShowaction()){
            actionArea.setVisibility(View.VISIBLE);
        }else{
            actionArea.setVisibility(View.GONE);
        }

        if (!cur.getStatus().equals("apply") && cur.getRelation_demand_id() > 0){
            talkApply.setEnabled(true);
        }else{
            talkApply.setEnabled(false);
        }

        if (!cur.getStatus().equals("quit")){
            talkQuit.setEnabled(true);
        }else{
            talkQuit.setEnabled(false);
        }


        talks = cur.getTalks();
        talkView.removeAllViews();
        for(Talk talk : talks){
            addOneTalk( talk );
        }
        Handler mHandler = new Handler();
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                chatScroll.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
        chatScroll.fullScroll(ScrollView.FOCUS_DOWN);
    }


    private void addOneTalk(final Talk talk ){

        View convertView;
        TextView thename;
        TextView thecontent;
        TextView thedate;
        CircleImageView thesnailview;
        ImageView info_snail;
        TextView title;
        TextView hint;
        TextView read;

        if (talk.getRelation_type().equals("")) {
            if (talk.getUser_id().equals(userId)) {
                convertView = LayoutInflater.from(TalkActivity.this).inflate(R.layout.activity_user_talk, null);

            } else {
                convertView = LayoutInflater.from(TalkActivity.this).inflate(R.layout.activity_relation_talk, null);
            }
        }else{
            if (talk.getUser_id().equals(userId)) {
                convertView = LayoutInflater.from(TalkActivity.this).inflate(R.layout.activity_user_info, null);

            } else {
                convertView = LayoutInflater.from(TalkActivity.this).inflate(R.layout.activity_relation_info, null);
            }
            title = (TextView) convertView.findViewById(R.id.info_title);
            info_snail = (ImageView) convertView.findViewById(R.id.info_snailview);
            hint = (TextView) convertView.findViewById(R.id.info_hint);

            if ( talk.getData().get("hint") !=null && !talk.getData().get("hint").equals("")) {
                hint.setText(talk.getData().get("hint"));
            }else{
                hint.setVisibility(View.GONE);
            }

            if ( talk.getData().get("title") !=null && !talk.getData().get("title").equals("")) {
                title.setText(talk.getData().get("title"));
            }else{
                title.setVisibility(View.GONE);
            }


            if (   StringUtil.notNullOrEmpty( talk.getData().get("snailview") )) {
                Picasso.with(this)
                        .load(talk.getData().get("snailview"))
                        .into(info_snail);
            }else{
                info_snail.setVisibility(View.GONE);
            }
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (talk.getRelation_type().equals("person")){
                        Intent intent = new Intent();
                        intent.putExtra("id",  talk.getRelation_id() );
                        intent.setClass(TalkActivity.this, PersonViewActivity.class);
                        startActivity(intent);
                    }else if (talk.getRelation_type().equals("demand") ){
                        Intent intent = new Intent();
                        intent.putExtra("id",  talk.getRelation_id() );
                        intent.setClass(TalkActivity.this, ChanceViewActivity.class);
                        startActivity(intent);
                    }else if (talk.getRelation_type().equals("org")) {
                        Intent intent = new Intent();
                        intent.putExtra("id",  talk.getRelation_id() );
                        intent.setClass(TalkActivity.this, OrgViewActivity.class);
                        startActivity(intent);
                    }else if (talk.getRelation_type().equals("relation")) {
                        Intent intent = new Intent();
                        intent.putExtra("mid",  talk.getRelation_id() );
                        intent.setClass(TalkActivity.this, RelationActivity.class);
                        startActivity(intent);
                    }else if (talk.getRelation_type().equals("pic")){
                        Intent intent = new Intent();
                        intent.putExtra("title", talk.getData().get("hint"));
                        intent.putExtra("link",  talk.getData().get("url") );
                        intent.setClass(TalkActivity.this, WebviewActivity.class);
                        startActivity(intent);
                    }else if (talk.getRelation_type().equals("url")){
                        Intent intent = new Intent();
                        intent.putExtra("title", talk.getData().get("hint"));
                        intent.putExtra("link",  talk.getData().get("url") );
                        intent.setClass(TalkActivity.this, WebviewActivity.class);
                        startActivity(intent);
                    }else if (talk.getRelation_type().equals("eperson")){
                        Intent intent = new Intent();
                        intent.putExtra("from", "chance"  );
                        intent.setClass(TalkActivity.this, AccountActivity.class);
                        startActivity(intent);
                    }else if (talk.getRelation_type().equals("edemand")){
                        Intent intent = new Intent();
                        intent.putExtra("id", talk.getRelation_id()  );
                        intent.setClass(TalkActivity.this, DemandNewActivity.class);
                        startActivity(intent);
                    }else if (talk.getRelation_type().equals("eorg")){
                        Intent intent = new Intent();
                        intent.putExtra("id", talk.getRelation_id()  );
                        intent.setClass(TalkActivity.this, OrgActivity.class);
                        startActivity(intent);
                    }else if (talk.getRelation_type().equals("verify")){
                        Intent intent = new Intent();
                        intent.setClass(TalkActivity.this, VerifyActivity.class);
                        startActivity(intent);
                    }
                }
            });

        }

        if (talk.getUser_id().equals(userId)){
            read =  (TextView) convertView.findViewById(R.id.user_read);
            if ( talk.getRead() == -1){
                read.setVisibility(View.GONE);
            }else if (talk.getRead() == 0){
                read.setVisibility(View.VISIBLE);
                read.setText("未读");
            }else{
                read.setVisibility(View.VISIBLE);
                read.setText("已读");
            }
        }

        thename = (TextView) convertView.findViewById(R.id.user_name);
        thecontent = (TextView) convertView.findViewById(R.id.user_description);
        thedate = (TextView) convertView.findViewById(R.id.user_date);
        thesnailview = (CircleImageView) convertView.findViewById(R.id.user_snailview);

        thesnailview.setTag(talk.getUser_id().toString());
        thename.setText(talk.getDisplayname());
        thecontent.setText(talk.getDescription());
        thedate.setText(talk.getCreated());
        if (StringUtil.notNullOrEmpty(talk.getSnailview())) {
            Picasso.with(this)
                    .load(talk.getSnailview())
                    .into(thesnailview);
        }

        thesnailview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent();
                intent.putExtra("id",Integer.parseInt( (String)view.getTag()) );
                intent.setClass(TalkActivity.this, PersonViewActivity.class);
                startActivity(intent);

            }
        });

        talkView.addView(convertView);
    }

    private void showOneTalk( String  desc ){
        SimpleDateFormat formatter   =   new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate   =   new Date(System.currentTimeMillis());//获取当前时间
        String   strDate   =   formatter.format(curDate);

        Talk newTalk = new Talk();
        newTalk.setCreated(strDate );
        newTalk.setUser_id( userId);
        newTalk.setDescription(  desc);
        newTalk.setSnailview( WoyaoooApplication.snailview);
        if (!type.equals("member")) {
            newTalk.setRead(0);
        }
        talks.add( newTalk );
        addOneTalk( newTalk );

        Handler mHandler = new Handler();
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                chatScroll.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
        chatScroll.fullScroll(ScrollView.FOCUS_DOWN);
    }

    private void showTypingIndicator() {
        if (! cur.getType().equals("ai")) {
            return;
        }else{
            Common.showSnack(TalkActivity.this,sendButton,"发送消息...");
        }

        if (typingIndicator != null) {
            return; // Already showing
        }

        View convertView = LayoutInflater.from(TalkActivity.this).inflate(R.layout.activity_relation_talk, null);
        TextView thename = (TextView) convertView.findViewById(R.id.user_name);
        TextView thecontent = (TextView) convertView.findViewById(R.id.user_description);
        TextView thedate = (TextView) convertView.findViewById(R.id.user_date);
        CircleImageView thesnailview = (CircleImageView) convertView.findViewById(R.id.user_snailview);

        // Get partner info from participants
        String partnerName = cur.getRelation_displayname();
        String partnerSnailview = cur.getRelation_snailview();
        if (CollectionUtil.notEmpty(cur.getParticipants())) {
            for (com.woyao.core.model.PartnerSummary partner : cur.getParticipants()) {
                if (!partner.getUser_id().equals(userId)) {
                    partnerName = partner.getDisplayname();
                    partnerSnailview = partner.getSnailview();
                    break;
                }
            }
        }

        thename.setText(partnerName);
        thecontent.setText("正在回复...");
        thedate.setText("");

        if (StringUtil.notNullOrEmpty(partnerSnailview)) {
            Picasso.with(this)
                    .load(partnerSnailview)
                    .into(thesnailview);
        }

        typingIndicator = convertView;
        talkView.addView(typingIndicator);

        Handler mHandler = new Handler();
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                chatScroll.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
    }

    private void hideTypingIndicator() {
        if (typingIndicator != null) {
            talkView.removeView(typingIndicator);
            typingIndicator = null;
        }
    }

    private void showCounterTalkReply(String replyContent) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());
        String strDate = formatter.format(curDate);

        Talk replyTalk = new Talk();
        replyTalk.setCreated(strDate);
        replyTalk.setUser_id(cur.getPartner_id() != null ? cur.getPartner_id() : tid);
        replyTalk.setDescription(replyContent);
        replyTalk.setRelation_type(""); // Important: set to empty string to avoid NullPointerException

        // Get partner info from participants
        String partnerName = cur.getRelation_displayname();
        String partnerSnailview = cur.getRelation_snailview();
        if (CollectionUtil.notEmpty(cur.getParticipants())) {
            for (com.woyao.core.model.PartnerSummary partner : cur.getParticipants()) {
                if (!partner.getUser_id().equals(userId)) {
                    partnerName = partner.getDisplayname();
                    partnerSnailview = partner.getSnailview();
                    break;
                }
            }
        }

        replyTalk.setDisplayname(partnerName);
        replyTalk.setSnailview(partnerSnailview);

        talks.add(replyTalk);
        addOneTalk(replyTalk);

        Handler mHandler = new Handler();
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                chatScroll.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
    }

    private void showAppoint( Appointment app ){
        SimpleDateFormat formatter   =   new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate   =   new Date(System.currentTimeMillis());//获取当前时间
        String   strDate   =   formatter.format(curDate);


        Map<String,String> data = new HashMap<String, String>();
        data.put("id",app.getId()) ;
        data.put("address",app.getAddress()) ;
        data.put("contact",app.getContact()) ;
        data.put("date",app.getDate()) ;
        data.put("time",app.getTime()) ;
        data.put("status",app.getStatus()) ;
        data.put("mode", app.getMode());
        data.put("message",app.getMessage());
        data.put("title",app.getTitle());



        Talk newTalk = new Talk();
        newTalk.setData( data);
        newTalk.setType(2);
        newTalk.setRelation_id( Integer.parseInt( app.getId()));
        newTalk.setCreated(strDate );
        newTalk.setUser_id( userId);
        newTalk.setDescription(  app.getDescription()   );
        newTalk.setSnailview( WoyaoooApplication.snailview);
        talks.add( newTalk );
        addOneTalk( newTalk );

        Handler mHandler = new Handler();
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                chatScroll.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
        chatScroll.fullScroll(ScrollView.FOCUS_DOWN);
    }

    private void sendTalk() {

        if (content.getText().toString().trim().equals("")){
            return;
        }
//        progressDialog = new ProgressDialog(this);
//        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//        progressDialog.setMessage("发送消息······");
//        progressDialog.show();


        final String desc = content.getText().toString();
        if (desc.equals("")) return;

        AsyncTask<Void, Void, BaseResponse> task = new AsyncTask<Void, Void, BaseResponse>() {
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // Show user's message immediately
                showOneTalk(desc);
                content.setText("");
                // Show typing indicator while waiting for server response

                showTypingIndicator();
            }

            @Override
            protected BaseResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                // Signal server to reply immediately by passing "reply" in data parameter
                Call<BaseResponse> responseCall = svc.talk(userId, cur.getId(),cur.getType(),desc,"reply");
                try {
                    BaseResponse r = responseCall.execute().body();
                    return r;
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }

            @Override
            protected void onPostExecute(final BaseResponse response) {
//                progressDialog.dismiss();
                // Hide typing indicator now that we received the response
                hideTypingIndicator();

                if (response == null){
                    Common.showSnack(TalkActivity.this,sendButton,"网络错误，请重试");
                    return;
                }
                if (response.isSuccess()) {
                    // Check if server provided immediate reply in response message
                    if (response.getMessage() != null && !response.getMessage().isEmpty()) {
                        // Show the server's reply as counter talker message
                        showCounterTalkReply(response.getMessage());
                    }

                    Timer timer = new Timer();
                    timer.schedule(new TimerTask() {

                        public void run() {
                            InputMethodManager inputManager = (InputMethodManager) content.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                            inputManager.showSoftInput(content, 0);
                        }

                    }, 500);

                    content.requestFocus();

                } else {
                    Common.alert(TalkActivity.this,response.getMessage());
                }

            }

            @Override
            protected void onCancelled() {
//                progressDialog.dismiss();
                // Hide typing indicator if request was cancelled
                hideTypingIndicator();
            }
        };
        task.execute((Void) null);
    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);


    }

}
